package com.leo.base;

import com.leo.util.json.JsonUtil;
import org.springframework.web.servlet.ModelAndView;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;

/**
 * controller父类
 *
 * @author liusl
 * @version 1.0
 * @date 2018/12/8 13:05
 */
public abstract class AbstractController {


    protected ModelAndView buildModelAndView(String modelName, Object param) {
        Map<String, Object> paramMap = object2Map(param);
        return buildModelAndView(modelName, paramMap);
    }

    private ModelAndView buildModelAndView(String modelName, Map<String, ?> paramsMap) {
        ModelAndView view = buildModelAndView(modelName);
        view.addAllObjects(paramsMap);
        return view;
    }

    protected ModelAndView buildModelAndView(String modelName) {
        return new ModelAndView(modelName);
    }

    protected ReturnResponse failure(int code, String message) {
        return new ReturnResponse(code,message);
    }

    protected String buildResult(ReturnResponse response) {
        return JsonUtil.toJSONString(response);
    }

    public static Map<String, Object> object2Map(Object object) {
        Map<String, Object> result = new HashMap<>();
        //获得类的的属性名 数组
        Field[] fields = object.getClass().getDeclaredFields();
        try {
            for (Field field : fields) {
                field.setAccessible(true);
                String name = new String(field.getName());
                result.put(name, field.get(object));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }
}
